<?php
/**
 * User: Tegic
 * Date: 2018/6/1
 * Time: 14:37
 */

namespace app\hander;


use think\facade\Cache;
use think\Response;

class HelpHander
{
	/**
	 *     通用数据输出
	 * @Function Response
	 *
	 * @param type $msg         输出提示信息
	 * @param type $code        状态码
	 * @param type $data        返回数组
	 * @param type $result_code 业务逻辑码 不指定默认和状态码一致
	 * @param type $header      header
	 * @param type $type        返回数据格式
	 *
	 * @return type
	 *
	 * @Author   tegic
	 * @Time     2018/6/1 14:38
	 */
	public static function Response($msg, $code = 200, $data = [], $result_code = null, $header = [], $type = 'json')
	{
		$result_code === null && $result_code = $code;
		$result          = [
			'code' => $result_code,
			'msg'  => $msg,
			'data' => $data,
		];
		$header['token'] = request()->token;
		$response        = Response::create($result, $type)->code($code)->header($header);
		throw new \think\exception\HttpResponseException($response);
		return;
	}
	
	/**
	 * 请求限制
	 * @Function limit
	 *
	 * @param  int $limit
	 * @param int  $minutes
	 * @param bool $token
	 *
	 * @return bool
	 * @Author   tegic
	 * @Time     2018/6/5 11:52
	 */
	public static function limit($limit, $minutes = 60, $token = false)
	{
		if (!$token) {
			$token = request()->token;
		}
		$url   = str_limit(base64_encode(request()->path()), 10);
		$count = cache('limit:' . $token . ':' . $url);
		if ($count >= $limit) {
			return false;
		}
		if (!$count) {
			cache('limit:' . $token . ':' . $url, 1, $minutes);
			return true;
		}
		Cache::inc('limit:' . $token . ':' . $url);
		return true;
	}
}